<template>
  <div class="lee-input">
    <!-- input -->
    <template v-if="type !== 'textarea'">
      <div style="width: 100%">
        <input
          :autofocus="autofocus"
          :class="[
            prefixIcon ? 'isPreIcon' : '',
            clearable || suffixIcon || showPassword ? 'isSubIcon' : '',
            size ? `input-${size}` : '',
          ]"
          ref="inputRef"
          :value="modelValue"
          :type="showPassword ? (passwordVisible ? 'text' : 'password') : type"
          :disabled="disabled"
          :placeholder="placeholder"
          @compositionstart="isComposing = true"
          @compositionend="handleCompositionEnd"
          @input="handleInput"
          @blur="handleBlur"
        />
        <!-- 清除按钮 -->
        <template v-if="clearable && modelValue">
          <lee-icon
            class="right-icon"
            icon="circle-xmark"
            @click="handleClear"
          ></lee-icon>
        </template>
        <!-- 密码按钮 -->
        <template v-if="showPassword && type === 'password' && modelValue">
          <lee-icon
            class="right-icon"
            :icon="!passwordVisible ? 'eye-slash' : 'eye'"
            @click="handleChangePasswordVisible"
          ></lee-icon>
        </template>
        <!-- 前置/后置图标 -->
        <template v-if="prefixIcon || suffixIcon">
          <lee-icon
            :class="{
              'left-icon': prefixIcon,
              'right-icon': suffixIcon,
            }"
            :icon="prefixIcon || suffixIcon"
          ></lee-icon>
        </template>
      </div>
    </template>
    <!--  textarea  -->
    <template v-else>
      <textarea
        :autofocus="autofocus"
        ref="textareaRef"
        :disabled="disabled"
        :placeholder="placeholder"
        :value="modelValue"
        @input="handleInput"
        :rows="rows"
      ></textarea>
    </template>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import prop from './props'
defineOptions({
  name: 'LeeInput',
  inheritAttrs: false,
})

const autofocus = ref(false)
const props = defineProps(prop)
const passwordVisible = ref(false)
const inputRef = ref(null)
const textareaRef = ref(null)
let isComposing = false
const emit = defineEmits(['update:modelValue', 'input', 'clear', 'blur'])
// 输入框
function handleInput(e) {
  // 当不在拼音输入时才触发事件
  if (!isComposing) {
    emit('update:modelValue', e.target.value)
    emit('input', e.target.value)
  }
}
// 失去焦点
function handleBlur() {
  emit('blur')
}
// 输入完成
function handleCompositionEnd(e) {
  isComposing = false
  emit('update:modelValue', e.target.value) // 输入完成后更新值
  emit('input', e.target.value)
}
// 清除文本
function handleClear() {
  emit('update:modelValue', '')
  emit('input', '')
  emit('clear')
}
// 改变输入框状态
function handleChangePasswordVisible() {
  passwordVisible.value = !passwordVisible.value
}
defineExpose({
  blur: () => {
    autofocus.value = true
  },
  clear: handleClear,
})
</script>
